/* eslint-disable no-use-before-define */
import { defineComponent, ref, withModifiers, watch, onMounted, SetupContext } from 'vue';
import { Color } from '../class/color.class';
import './scss/alpha.scss';
import { alphaProps, AlphaProps } from './props/alpha.props';

export default defineComponent({
    name: 'Alpha',
    props: alphaProps,
    emits: ['update:color'] as string[] | undefined,
    setup(props: AlphaProps, context: SetupContext) {
        const elementRef = ref<HTMLDivElement | null>(null);
        const thumbRef = ref<HTMLDivElement | null>(null);
        const randomId = ref(props.randomId);
        const allowColorNull = ref(props.allowColorNull);

        const changePointerPosition = (alpha: number) => {
            const x = Math.max(0, Math.min(alpha * 100, 100));
            const orientation = 'left';
            if (thumbRef.value) {
                const thumbRefValue = thumbRef.value;
                thumbRefValue.style?.setProperty(orientation, `${x}%`);
            }
        };

        class clickValue {
            x = 0;

            y = 0;

            height = 0;

            width = 0;
        }
        function calculateCoordinates(event: MouseEvent | TouchEvent): void {
            if (elementRef.value) {
                const { width: elWidth, height: elHeight, top: elTop, left: elLeft } = elementRef.value.getBoundingClientRect();

                const { pageX, pageY } = 'touches' in event ? event.touches[0] : event;

                const x = Math.max(0, Math.min(pageX - (elLeft + window.pageXOffset), elWidth));
                const y = Math.max(0, Math.min(pageY - (elTop + window.pageYOffset), elHeight));

                movePointer({ x, y, height: elHeight, width: elWidth });
            }
        }
        /** 修改禁止点击状态 */
        function changeBorderAndButtonStates() {
            // 选择颜色后，取消「确定」按钮的禁用状态
            const isCommitBtnDisabled = document.getElementById(`farris-color-picker-plus-sure-${randomId.value}`) as HTMLElement;
            isCommitBtnDisabled.className = 'btn btn-secondary';
            // 选择颜色后，取消输入框的红色警示状态;
            const isCommitBtnNull = document.getElementById(`farris-color-picker-plus-input-${randomId.value}`) as HTMLElement;
            isCommitBtnNull.style.borderColor = '#dcdfe6';
        }
        const movePointer = ({ x, width }: clickValue) => {
            const alpha = x / width;
            changePointerPosition(alpha);
            changeBorderAndButtonStates();
            const hsva = props.color.getHsva();
            const newColor = new Color().setHsva(hsva.hue, hsva.saturation, hsva.value, alpha);

            if (props.color != null) {
                context.emit('update:color', newColor);
            } else if (props.color == null && allowColorNull.value) {
                context.emit('update:color', null);
            }
        };

        onMounted(() => {
            const hsva = props.color.getHsva();
            changePointerPosition(hsva.alpha);
        });

        watch(
            () => props.color,
            (newValue) => {
                const hsva = newValue.getHsva();
                changePointerPosition(hsva.alpha);
            }
        );
        return () => (
            <div
                class="f-alpha-component"
                ref={elementRef}
                onMousedown={withModifiers((payload: MouseEvent) => calculateCoordinates(payload), ['prevent'])}
                onTouchstart={withModifiers((payload: MouseEvent) => calculateCoordinates(payload), ['prevent'])}>
                <div class="color-alpha-slider__bar"> </div>
                <div class="color-alpha-slider__thumb" ref={thumbRef}></div>
            </div>
        );
    }
});
